<template>
  <Dialog :title="$t('调单')" width="65%" :footer="false" v-model="transferOrderVisible" @close="close()">
    <el-form label-width="80px" :model="transferPage" ref="transferRefForm">
      <el-row :gutter="24">
        <el-col :span="16" :xs="24">
          <el-form-item :label="$t('营销APP')" prop="appId"
                        style="display:flex"
                        :rules="[{required:true,trigger: 'change',message: $t('请选择')}]">
            <el-select style="width:47%" v-model="transferPage.appId" clearable>
              <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                         :value="item.appId"></el-option>
            </el-select>
            <span> - </span>
            <el-select style="width:47%" :placeholder="$t('营销员')" v-model="transferPage.systemUserId" clearable>
              <el-option v-for="item in marketStaffList" :key="item.systemUserId" :label="item.name"
                         :value="item.systemUserId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('用户姓名')">
            <el-input v-model="transferPage.name"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('手机号码')">
            <el-input v-model="transferPage.phone"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('营销状态')">
            <el-select style="width: 100%" v-model="transferPage.status" clearable>
              <el-option v-for="item in marketStatusList" :key="item.key" :label="item.value"
                         :value="item.key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('跟进次数')">
            <el-input v-model="transferPage.followUpNum">
              <template #prepend>
                <el-select style="width: 60px" v-model="transferPage.followUpSymbol">
                  <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('营销结果')">
            <el-cascader
                style="width: 100%"
                v-model="transferPage.causeKey"
                :options="selectCause"
                :props="{ checkStrictly: true,value:'key',label:'value' }"
                clearable></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('客户类型')">
            <el-select style="width: 100%" v-model="transferPage.type" clearable>
              <el-option :label="$t('数据用户')" :value="1"></el-option>
              <el-option :label="$t('流量用户')" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" :xs="24">
          <el-form-item :label="$t('分单时间')">
            <el-date-picker
                style="width: 100%"
                v-model="transferPage.distributeTime"
                type="daterange"
                range-separator="~"
                value-format="x"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item label-width="20px">
            <el-button type="primary" @click="getTableData">{{ $t('查询') }}</el-button>
            <el-button @click="resetSearch">{{ $t('重置') }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin-bottom: 10px;text-align: right">
      <el-button type="primary" @click="distribute('select')">{{ $t('所选分配') }}</el-button>
      <el-button type="primary" @click="distribute('search')">{{ $t('所搜分配') }}</el-button>
    </div>

    <Table v-model:selectRows="selectRows" :selection="true" :tableColumn="tableColumn" :tableData="tableData"
           @handleCurrentChange="(val)=>{transferPage.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{transferPage.pageSize = val,getTableData()}"
           :page="transferPage">
      <template #cause="{row}">
        <span v-if="row.cause1">
         {{ renderCause(row) }}
        </span>
      </template>
    </Table>

    <Dialog :title="distributeType === 'select' ? $t('所选分配') : $t('所搜分配')"
            @confirm="distributeConfirm"
            :confirmLoading="distributeConfirmLoading"
            @cancel="distributionVisible = false,distributePage = {}" v-model="distributionVisible" appendBody>
      <el-form label-width="80px" :model="distributePage">
        <el-row :gutter="24">
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('员工姓名')">
              <el-input clearable v-model="distributePage.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('账号')">
              <el-input clearable v-model="distributePage.account"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item>
              <el-button type="primary" @click="getMarketStaff">{{ $t('查询') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Table :tableData="distributeTableData" :page="false" v-model:selectRows="distributeSelectRows"
             :selection="true">
        <el-table-column :label="$t('员工姓名')" prop="name" align="center"></el-table-column>
        <el-table-column :label="$t('账号')" prop="account" align="center"></el-table-column>
      </Table>
    </Dialog>
  </Dialog>
</template>

<script>
import {onMounted, reactive, ref, toRefs, watch} from "vue";
import i18n from '@/locale/index'
import {marketingJustSelect, marketingJustSearch, fetchMarketingJustList} from "@/api/market"
import {dateFormatTimeStamp, getMarketCause} from "@/utils";
import {ElMessage} from "element-plus"
import {selectSystemUser} from "@/api";

const $t = i18n.global.t
const tableColumn = [
  {label: $t('客户类型'), prop: 'type', align: 'center'},
  {label: $t('用户姓名'), prop: 'name', align: 'center'},
  {label: $t('手机号码'), prop: 'phone', align: 'center'},
  {label: $t('分单时间'), prop: 'creationTime', align: 'center', minWidth: 150},
  {label: $t('营销结果'), prop: 'cause', slot: 'cause', align: 'center', minWidth: 150},
  {label: $t('跟进次数'), prop: 'followUpNum', align: 'center'},
  {label: $t('最新跟进时间'), prop: 'followUpTime', align: 'center', minWidth: 150},
  {label: $t('营销APP'), prop: 'appName', align: 'center'},
  {label: $t('营销员'), prop: 'systemUserName', align: 'center'},
]
export default {
  name: "transferOrder",
  props: ['transferOrderVisible', 'productList', 'marketStaffList', 'selectCause'],
  setup(props, {emit}) {
    const transferRefForm = ref(null)
    const state = reactive({
      transferPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        followUpSymbol: '='
      },
      marketStatusList: [
        {key: 1, value: $t('未注册')},
        {key: 2, value: $t('未申请')},
      ],
      symbolList: [
        {label: '>', value: '>'},
        {label: '=', value: '='},
        {label: '≧', value: '>='},
        {label: '≦', value: '<='},
        {label: '<', value: '<'}
      ],
      selectRows: [],
      tableData: [],
      distributeTableData: [],
      distributeType: '',
      distributePage: {},
      distributionVisible: false,
      distributeConfirmLoading: false,
      distributeSelectRows: []
    })
    watch(() => props.transferOrderVisible, (value) => {
      if (!value) {
        transferRefForm.value.resetFields()
        state.transferPage = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
      }
    })
    const methods = {
      async getTableData() {
        transferRefForm.value.validate(async v => {
          console.log(v)
          if (v) {
            const [distributeTimeStart, distributeTimeEnd] = dateFormatTimeStamp(state.transferPage.distributeTime)
            const [cause1, cause2] = state.transferPage.causeKey || []
            const params = {
              ...state.transferPage,
              distributeTimeStart, distributeTimeEnd,
              cause1, cause2,
              distributeTime: null,
              causeKey: null
            }
            const res = await fetchMarketingJustList(params)
            if (res.code === 200) {
              const {list, total} = res.data
              state.tableData = list.map(item => {
                item.type = item.type === 1 ? $t('数据用户') : $t('流量用户')
                return item
              })
              state.transferPage.total = total
            }
          }
        })
      },
      resetSearch() {
        state.transferPage = {
          pageNum: 1,
          pageSize: 10,
          total: 0,
          followUpSymbol: '='
        }
        state.tableData = []
      },
      renderCause(row) {
        const {value: cause1} = getMarketCause().find(item => item.key === row.cause1)
        const {value: cause2} = getMarketCause().find(item => item.key === row.cause2)
        return cause1 ? cause1 + ' - ' + cause2 : ''
      },
      async distribute(value) {
        if (value === 'select' && state.selectRows.length === 0) {
          return ElMessage.error('请选择订单')
        }
        state.distributeType = value
        await methods.getMarketStaff()
        state.distributionVisible = true
      },
      async getMarketStaff() {
        const res = await selectSystemUser({marketingSwitch: 1, ...state.distributePage, status: 1})
        if (res.code === 200) {
          state.distributeTableData = res.data
        }
      },
      // 分配提交
      async distributeConfirm() {
        if (state.distributeSelectRows.length === 0) return ElMessage.error($t('请选择员工'))
        let params = {}
        if (state.distributeType === 'select') {
          // 所选
          params['ids'] = state.selectRows.map(item => item.id)
          params['systemUserIds'] = state.distributeSelectRows.map(item => item.systemUserId)
        } else {
          // 所搜
          const [distributeTimeStart, distributeTimeEnd] = dateFormatTimeStamp(state.transferPage.distributeTime)
          params = {
            ...state.transferPage,
            distributeTimeStart, distributeTimeEnd,
            distributeTime: null,
            systemUserIds: state.distributeSelectRows.map(item => item.systemUserId)
          }
        }
        state.distributeConfirmLoading = true
        const api = (params) => state.distributeType === 'select' ? marketingJustSelect(params) : marketingJustSearch(params)
        const res = await api(params)
        if (res.code === 200) {
          ElMessage.success($t('操作成功'))
          state.distributionVisible = false
          methods.getTableData()
        }
        state.distributeConfirmLoading = false
      },
      close() {
        emit('update:transferOrderVisible', false)
      },
    }
    return {
      transferRefForm,
      ...toRefs(state),
      tableColumn,
      ...methods
    }
  }
}
</script>

<style scoped>

</style>
